package com.rw.coco.api.data.persistence.simple;

import com.rw.coco.api.data.model.CharacterPropertyModel;
import com.rw.coco.api.data.persistence.CharacterPropertyMapper;

import java.util.HashSet;
import java.util.Set;

/**
 * 简单实现CharacterPropertyMapper类
 * 注意，如果实现这个类，则不保证调用原子性
 */
public abstract class SimpleCharacterPropertyMapper implements CharacterPropertyMapper,
        BaseSimpleMapper<CharacterPropertyModel> {
    /**
     * 获取指定角色的所有属性
     *
     * @param characterId 角色的ID
     */
    @Override
    public Set<CharacterPropertyModel> getProperties(int characterId) {
        CharacterPropertyModel select = new CharacterPropertyModel();
        select.setCharacterId(characterId);
        return new HashSet<>(selectList(select));
    }

    /**
     * 设置指定角色的属性
     *
     * @param properties 需要设置的属性
     */
    @Override
    public void setProperties(Set<CharacterPropertyModel> properties) {
        insertAll(properties);
    }

    /**
     * 删除指定角色的指定的某条属性
     *
     * @param characterId    角色id
     * @param propertiesName 角色属性名
     */
    @Override
    public void deleteProperties(int characterId, String propertiesName) {
        CharacterPropertyModel delete = new CharacterPropertyModel();
        delete.setCharacterId(characterId);
        delete.setPropertiesName(propertiesName);
        deleteAll(delete);
    }

    /**
     * 删除指定角色的所有属性
     *
     * @param characterId 角色的ID
     */
    @Override
    public void deleteAllProperties(int characterId) {
        CharacterPropertyModel delete = new CharacterPropertyModel();
        delete.setCharacterId(characterId);
        deleteAll(delete);
    }

    /**
     * 增加角色指定的属性值
     *
     * @param characterId 角色ID
     * @param propName    属性值
     * @param addValue    增加的值
     */
    @Override
    public void addPropValue(int characterId, String propName, int addValue) {
        CharacterPropertyModel select = new CharacterPropertyModel(characterId, propName, null);

        CharacterPropertyModel result = selectList(select).stream()
                .findFirst()
                .orElseThrow(IllegalArgumentException::new);

        result.setPropertiesValue(result.getPropertiesValue() + addValue);

        update(result);
    }
}
